import cv2

# 全局变量存储选择区域坐标
roi_coordinates = {'x1': 0, 'y1': 0, 'x2': 0, 'y2': 0}
drawing = False  # 标记是否正在绘制


def select_region(event, x, y, flags, param):
    """ 鼠标回调函数，处理区域选择 """
    global roi_coordinates, drawing

    if event == cv2.EVENT_LBUTTONDOWN:  # 鼠标左键按下
        drawing = True
        roi_coordinates = {'x1': x, 'y1': y, 'x2': x, 'y2': y}

    elif event == cv2.EVENT_MOUSEMOVE:  # 鼠标移动
        if drawing:
            roi_coordinates['x2'] = x
            roi_coordinates['y2'] = y

    elif event == cv2.EVENT_LBUTTONUP:  # 鼠标左键释放
        drawing = False
        roi_coordinates['x2'] = x
        roi_coordinates['y2'] = y


def preview_video(video_path, frame_num=0):
    """
    视频预览与区域选择工具
    :param video_path: 视频文件路径
    :param frame_num: 要预览的帧序号（默认第0帧）
    """
    global roi_coordinates, drawing  # 添加全局声明
    #
    # cap = cv2.VideoCapture(video_path)
    # if not cap.isOpened():
    #     raise ValueError("无法打开视频文件")
    cap =cv2.VideoCapture(0);
    # 跳转到指定帧
    # cap.set(cv2.CAP_PROP_POS_FRAMES, frame_num)
    ret, frame = cap.read()
    if not ret:
        raise ValueError("无法读取指定帧")

    # 创建窗口并绑定鼠标事件
    cv2.namedWindow('Select ROI')
    cv2.setMouseCallback('Select ROI', select_region)

    clone = frame.copy()
    while True:
        current_frame = clone.copy()

        # 实时绘制选择框
        if roi_coordinates['x1'] != roi_coordinates['x2'] and roi_coordinates['y1'] != roi_coordinates['y2']:
            cv2.rectangle(current_frame,
                          (roi_coordinates['x1'], roi_coordinates['y1']),
                          (roi_coordinates['x2'], roi_coordinates['y2']),
                          (0, 255, 0), 2)

            # 显示坐标信息
            info = f"X: {min(roi_coordinates['x1'], roi_coordinates['x2'])}-{max(roi_coordinates['x1'], roi_coordinates['x2'])}"
            info2 = f"Y: {min(roi_coordinates['y1'], roi_coordinates['y2'])}-{max(roi_coordinates['y1'], roi_coordinates['y2'])}"
            cv2.putText(current_frame, info, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
            cv2.putText(current_frame, info2, (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)

        cv2.imshow('Select ROI', current_frame)

        # 键盘控制
        key = cv2.waitKey(1) & 0xFF

        # 按R重置选择
        if key == ord('r'):
            clone = frame.copy()
            roi_coordinates = {'x1': 0, 'y1': 0, 'x2': 0, 'y2': 0}  # 现在可以正确修改全局变量

        # 按Q确认并退出
        elif key == ord('q'):
            break

    cv2.destroyAllWindows()
    cap.release()

    # 计算最终区域参数
    x = min(roi_coordinates['x1'], roi_coordinates['x2'])
    y = min(roi_coordinates['y1'], roi_coordinates['y2'])
    w = abs(roi_coordinates['x1'] - roi_coordinates['x2'])
    h = abs(roi_coordinates['y1'] - roi_coordinates['y2'])

    return (x, y, w, h) if w > 0 and h > 0 else None


# 使用示例
if __name__ == "__main__":
    # video_path = r"E:\photo\video\1.mp4"
    # 选择起始帧（可以修改为需要的帧号）
    selected_region = preview_video("", frame_num=0)

    if selected_region:
        print(f"选择的区域参数：{selected_region}")
        print("区域格式 (x, y, width, height)")
        print("可以将此参数用于之前的拆帧函数")
    else:
        print("未选择有效区域")